/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.utfpr.dao;

import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import pojo.Cliente;

public class DaoCliente {

    public DaoCliente() {
    }

    public Cliente salvar(Cliente cliente) {
        EntityManager entityManager = Conexao.getInstance().createEntityManager();

        entityManager.getTransaction().begin();
        
        cliente = entityManager.merge(cliente);
        
        entityManager.getTransaction().commit();

        entityManager.close();
        
        return cliente;
    }
    
    public void excluir(Long id) throws Exception{
        EntityManager entityManager = Conexao.getInstance().createEntityManager();
        entityManager.getTransaction().begin();
        Cliente c = entityManager.find(Cliente.class, id);
        
        try {
            if(c != null)
                entityManager.remove(c);
            else
               throw new Exception("O registro não existe mais, tente reconsultá-lo."); 
        } catch (Exception e) {
            if (e.getMessage().contains("Code: 1451")) {
                throw new Exception("Registro utilizado em outra tabela.");
            } else {
                throw new Exception("Erro desconhecido ao excluir.");
            }
        }
        
        entityManager.getTransaction().commit();

        entityManager.close();
    }
    
    public List<Cliente> pesquisarPorNome(String nome){
        EntityManager entityManager = Conexao.getInstance().createEntityManager();
        List<Cliente> lista = entityManager.createQuery("select c from Cliente c where c.nome like '%"+nome+"%'").getResultList();
        System.out.println(lista.toString());
        return lista;
    }
}
